<template>
  <div class="like-container">
    <LayoutHeaderTitle title="我的收藏">
      <template #right>
        <div class="right-header">
          <van-icon
            name="search"
            @click="$router.push({ name: 'user-likeSearch' })"
          />
          <span @click="isManage = !isManage" :class="isManage ? 'active' : ''">
            管理
            <van-icon name="cross" />
          </span>
        </div>
      </template>
    </LayoutHeaderTitle>
    <div class="like-wrapper">
      <div class="like-option">
        <van-dropdown-menu direction="down">
          <van-dropdown-item ref="goodsStatus">
            <template #title>
              <span :class="goodsStatus ? 'active' : ''">宝贝状态</span>
            </template>
            <span
              v-for="item in goodsOpt"
              @click="chooseItem('goodsStatus', item.value)"
              :class="goodsStatus === item.value ? 'active' : ''"
              :key="item.value"
            >
              {{ item.text }}
            </span>
          </van-dropdown-item>
          <van-dropdown-item ref="time">
            <template #title>
              <span :class="time ? 'active' : ''">收藏时间</span>
            </template>
            <span
              v-for="item in timeOpt"
              @click="chooseItem('time', item.value)"
              :class="time === item.value ? 'active' : ''"
              :key="item.value"
            >
              {{ item.text }}
            </span>
          </van-dropdown-item>
          <van-dropdown-item ref="category">
            <template #title>
              <span :class="category ? 'active' : ''">全部分类</span>
            </template>
            <span
              v-for="item in categoryList"
              @click="chooseItem('category', item.category_id)"
              :class="category === item.category_id ? 'active' : ''"
              :key="item.category_id"
            >
              {{ item.category_name }}
            </span>
          </van-dropdown-item>
        </van-dropdown-menu>
      </div>
      <LoadList
        @next="getNextList"
        v-if="likeList.length"
        :load="listLoad"
        :finished="finished"
      >
        <ul class="list">
          <li v-for="item in likeList" :key="item.g_id">
            <div class="warpper cl">
              <div class="checkbox" v-show="isManage">
                <van-checkbox
                  :value="getChecked(item.like_id)"
                  @click="select(item.like_id)"
                />
              </div>
              <nuxt-link :to="item.g_id | goodsUrl" class="img">
                <img :src="item.g_src | formatSrc" :alt="item.g_name" />
              </nuxt-link>
              <div class="info">
                <nuxt-link :to="item.g_id | goodsUrl" class="title text-over2">
                  {{ item.g_name }}
                </nuxt-link>
                <div class="num">{{ item.like_num }}人收藏</div>
                <div class="price" v-if="item.g_status === '正常'">
                  <small>￥</small
                  >{{ item.discounted_price || item.sell_price }}
                </div>
                <span class="lapse" v-else>已失效</span>
                <div class="btn" v-show="!isManage">
                  <nuxt-link
                    v-show="item.g_status !== '正常'"
                    :to="{ name: 'store-id', params: { id: item.b_id } }"
                  >
                    去店铺
                  </nuxt-link>
                  <nuxt-link
                    :to="{
                      name: 'all-goods',
                      query: { category_name: item.category_name }
                    }"
                  >
                    找相似
                  </nuxt-link>
                </div>
              </div>
            </div>
          </li>
        </ul>
      </LoadList>
      <GoodsEmpty v-else img="like" title="暂无收藏商品" />
    </div>
    <div class="fixed-bottom" v-show="isManage">
      <van-checkbox @click="changeAllChecked" :value="allChecked">
        {{ allChecked ? "取消" : "" }}全选
      </van-checkbox>
      <van-button type="danger" size="small" class="del" @click="del">
        删除
      </van-button>
    </div>
  </div>
</template>
<script>
export default {
  middleware: "authenticated",
  layout: "notabbar",
  async asyncData({ app }) {
    let categoryList = [],
      likeList = [],
      finished = true,
      page = 1;
    try {
      const {
        data,
        page: p,
        status,
        total,
        pagesize: ps
      } = await app.$apiGetUserLike();
      if (status === 0) {
        likeList = data;
        page = p + 1;
        finished = p * ps >= total;
      }
    } catch (error) {}
    try {
      const { data } = await app.$apiGetGoodsCategory();
      categoryList = data;
    } catch (error) {}
    return {
      categoryList,
      likeList,
      finished,
      page
    };
  },
  data() {
    return {
      isManage: false,
      goodsOpt: [
        {
          text: "低库存",
          value: "lowStock"
        },
        {
          text: "失效",
          value: "lapse"
        },
        {
          text: "已买过",
          value: "buy"
        }
      ],
      timeOpt: [
        {
          text: "7天内",
          value: 7
        },
        {
          text: "30天内",
          value: 30
        },
        {
          text: "90天内",
          value: 90
        },
        {
          text: "半年前",
          value: "halfYear"
        },
        {
          text: "一年前",
          value: "year"
        }
      ],
      categoryOpt: [],
      goodsStatus: null,
      time: null,
      categoryList: [],
      likeList: [],
      category: null,
      listLoad: false,
      finished: true,
      checkedList: []
    };
  },
  methods: {
    chooseItem(key, val) {
      const { goodsStatus, time, category } = this;
      const data = {
        goodsStatus,
        time,
        category,
        [key]: val,
        page: 1
      };
      if (this[key] === val) {
        delete data[key];
      }
      this.getList(data, false).then(() => {
        this.$refs[key].toggle();
        this[key] = this[key] === val ? null : val;
      });
    },
    getList(data, isConcat) {
      this.listLoad = true;
      this.finished = true;
      return new Promise((resolve, reject) => {
        const loading = this.$helperLoadding();
        this.$apiGetUserLike(data)
          .then(res => {
            const { page, pagesize, total, status, data } = res;
            if (status === 0) {
              this.page = page + 1;
              this.finished = page * pagesize >= total;
              if (isConcat) {
                this.likeList = this.likeList.concat(data);
                return;
              }
              this.likeList = data;
            }
          })
          .finally(() => {
            loading.close();
            this.listLoad = false;
            resolve();
          });
      });
    },
    // 下一页
    getNextList() {
      const { goodsStatus, time, category, page } = this;
      const data = {
        goodsStatus,
        time,
        category,
        page
      };
      this.getList(data, true);
    },
    // 选中商品
    select(like_id) {
      let index = this.checkedList.findIndex(i => i === like_id);
      if (!~index) {
        return this.checkedList.push(like_id);
      }
      this.checkedList.splice(index, 1);
    },
    // 获取单个商品选中状态
    getChecked(like_id) {
      return this.checkedList.includes(like_id);
    },
    // 点击切换全选状态
    changeAllChecked() {
      let flag = this.allChecked;
      if (flag) {
        this.checkedList = [];
      } else {
        this.checkedList = this.likeList.map(i => i.like_id);
      }
    },
    del() {
      let len = this.checkedList.length;
      if (!len) {
        return this.$toast({ message: "你还未选择商品", type: "fail" });
      }
      this.$apiDelChooseLike({ like_id: this.checkedList }).then(res => {
        if (res.status === 0) {
          const { goodsStatus, time, category } = this;
          this.getList({ goodsStatus, time, category, page: 1 }).then(() => {
            this.checkedList = [];
          });
        }
      });
    }
  },
  computed: {
    allChecked() {
      if (this.likeList.length === 0) return false;
      return this.likeList.every(item => this.getChecked(item.like_id));
    }
  }
};
</script>
<style lang="scss" scoped src="./like.scss"></style>
